package oop.controller.action.question;

import java.util.List;

import oop.controller.action.DefaultAction;
import oop.data.BaseQuestion;
import oop.db.dao.BaseQuestionDAO;

import org.apache.commons.lang.StringUtils;

public class ListAction extends DefaultAction {

	public static final int PAGE_LENGTH = 2;

	@Override
	public void perform() throws Exception {

		String pageStr = StringUtils.defaultIfEmpty(request
				.getParameter("page"), "1");
		int page = Integer.parseInt(pageStr);

		List<BaseQuestion> questions;
		int count;
		if (request.getParameter("category") != null) {
			int id = Integer.parseInt(request.getParameter("category"));
			questions = BaseQuestionDAO.fetchByCategory(id, (page - 1) * PAGE_LENGTH,
					PAGE_LENGTH);
			count = BaseQuestionDAO.countByCategory(id);
		} else if (request.getParameter("author") != null) {
			int id = Integer.parseInt(request.getParameter("author"));
			questions = BaseQuestionDAO.fetchByAuthor(id, (page - 1) * PAGE_LENGTH,
					PAGE_LENGTH);
			count = BaseQuestionDAO.countByAuthor(id);
		} else {
			questions = BaseQuestionDAO.fetch((page - 1) * PAGE_LENGTH, PAGE_LENGTH);
			count = BaseQuestionDAO.count();
		}

		request.setAttribute("questions", questions);
		request.setAttribute("page", page);
		request.setAttribute("pageCount", (int) Math.ceil(count
				/ (double) PAGE_LENGTH));
	}

}
